#include "cdelegate.h"

CDelegate::CDelegate(QObject *parent):QStyledItemDelegate(parent)
{

}

void CDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    painter->save();

    //paint抗锯齿
    painter->setRenderHint(QPainter::SmoothPixmapTransform);
    painter->setRenderHint(QPainter::Antialiasing);
    painter->setRenderHint(QPainter::HighQualityAntialiasing);

    //获得数据字符串
    QString dataStr = index.data(Qt::UserRole).value<QString>();

    //画标签
    if (!dataStr.isEmpty())
    {
        //构建圆角背景rect
        QRectF roundedBackRect;
        roundedBackRect.setX(option.rect.x());
        roundedBackRect.setY(option.rect.y());
        roundedBackRect.setWidth(this->sizeHint(option, index).width());
        roundedBackRect.setHeight(44);

        //画圆角背景
        painter->setBrush(QColor("#D5DBEE"));
        painter->drawRoundedRect(roundedBackRect, 22, 22);

        //画字
        QFont font_yahei_20;
        font_yahei_20.setFamily("Microsoft YaHei UI");
        font_yahei_20.setPixelSize(20);
        QPoint contentPoint(option.rect.x() + 20, option.rect.y() + (this->sizeHint(option, index).height() - font_yahei_20.pixelSize()) / 2  + font_yahei_20.pixelSize() - 2);
        painter->setFont(font_yahei_20);
        painter->drawText(contentPoint, dataStr);
    }
}

QSize CDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionViewItem o = option;
    QStyle::State s = o.state;

    //获得数据字符串
    QString dataStr = index.data(Qt::UserRole).value<QString>();

    //获得数据字符串的长度
    QFont font_yahei_20;
    font_yahei_20.setFamily("Microsoft YaHei UI");
    font_yahei_20.setPixelSize(20);
    QFontMetrics metrix(font_yahei_20);
    QRect font_rect = metrix.boundingRect(dataStr);
    int dataStrWidth = font_rect.width();

    //构造项的大小
    QSize size;
    int h_padding = 20;//左右内边距
    size.setWidth(h_padding*2+dataStrWidth);
    size.setHeight(44);

    return size;
}
